/*
 * Copyright 2013 Sigurd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.digiway.rapidbreeze.server.model.download.action;

import de.digiway.rapidbreeze.server.model.download.DownloadManager;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Sigurd
 */
public class DownloadManagerActionExecutor {

    private LinkedBlockingQueue<FutureTask<?>> queue;
    private ThreadLocal<Boolean> inAction;
    private Executor executor;
    private RunnableExecutor runnableExecutor;
    private static final Logger LOG = Logger.getLogger(DownloadManagerActionExecutor.class.getName());

    public DownloadManagerActionExecutor() {
        this.queue = new LinkedBlockingQueue<>();
        this.executor = Executors.newSingleThreadExecutor();
        this.runnableExecutor = new RunnableExecutor();
        this.inAction = new ThreadLocal<Boolean>() {
            @Override
            protected Boolean initialValue() {
                return false;
            }
        };
    }

    /**
     * Starts the thread which consumes and executes the given actions.
     */
    public void start() {
        this.inAction.set(false);
        this.executor.execute(runnableExecutor);
    }

    /**
     * Stops the executor thread. The current and all pending
     * {@linkplain DownloadManagerAction} will still be executed.
     */
    public void stop() {
        FutureTask<PoisonPill> poisonTask = new FutureTask<>(new Callable<PoisonPill>() {
            @Override
            public PoisonPill call() throws Exception {
                return new PoisonPill();
            }
        });

        queue.offer(poisonTask);
    }

    /**
     * Executes the given {@linkplain DownloadManagerAction} and returns a
     * {@linkplain Future} object of the result.
     *
     * @param action
     */
    public <V> Future<V> executeAction(DownloadManagerAction<V> action) {
        try {
            if (inAction.get()) {
                return new SimpleFuture<>(action.call());
            }
            FutureTask<V> task = new FutureTask<>(action);
            queue.offer(task);
            return task;
        } catch (Exception ex) {
            throw new IllegalStateException("Error executing " + DownloadManager.class.getSimpleName() + " action.", ex);
        }
    }

    private class RunnableExecutor implements Runnable {

        @Override
        public void run() {
            while (true) {
                try {
                    FutureTask<?> task = queue.take();
                    inAction.set(true);
                    task.run();
                    if (task.get() instanceof PoisonPill) {
                        break;
                    }
                } catch (RuntimeException | ExecutionException ex) {
                    LOG.log(Level.SEVERE, "An exception occured during execution of an " + DownloadManager.class.getSimpleName() + " action. Continue execution...", ex);
                } catch (InterruptedException ex) {
                    LOG.log(Level.SEVERE, DownloadManager.class.getSimpleName() + " action executor interrupted.", ex);
                    break;
                } finally {
                    inAction.set(false);
                }
            }
        }
    }

    private static class PoisonPill {
    }

    private static class SimpleFuture<V> implements Future<V> {

        private V result;

        public SimpleFuture(V result) {
            this.result = result;
        }

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return false;
        }

        @Override
        public boolean isCancelled() {
            return false;
        }

        @Override
        public boolean isDone() {
            return true;
        }

        @Override
        public V get() throws InterruptedException, ExecutionException {
            return result;
        }

        @Override
        public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
            return get();
        }
    }
}
